package com.tdu.spider.biz.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.net.ssl.SSLContext;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * TODO: detail description
 *
 * @author tangdu@qccr.com
 * @version $: HttpUtils.java, v 0.1 2017年12月2017/12/1日 下午2:16 tangdu Exp $
 * @name TODO: HttpUtils
 */
public class HttpUtils {
    final static String ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";

    public static CloseableHttpClient httpClient() throws Exception {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .setUserAgent(ua)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(sslContext).build();
        return httpClient;
    }

    public static String getSSLContent(String url) throws Exception {
        Response response = Executor.newInstance(httpClient()).execute(Request.Get(url).userAgent(ua));
        String string = response.returnContent().asString(Charset.forName("UTF-8"));
        return string;
    }

    public static String getContent(String url) throws Exception {
        Response response = Request.Get(url).userAgent(ua).execute();
        String string = response.returnContent().asString(Charset.forName("UTF-8"));
        return string;
    }
}
